package com.wrb.points.controller.microservice;

import com.wrb.points.exception.ServiceException;
import com.wrb.points.model.Points;
import com.wrb.points.response.ResponseCode;
import com.wrb.points.response.ServerResponse;
import com.wrb.points.service.PointsService;
import com.wrb.points.utils.SnowflakeIdWorker;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * @author Wrb
 * @date 2019/12/20 16:10
 */
@RestController
@RequestMapping("/micro/points")
@CrossOrigin(origins = "*", methods = {RequestMethod.POST, RequestMethod.GET})
@Api(tags = "积分服务内部调用")
public class MicroPointsController {

	@Autowired
	private PointsService pointsService;

	@RequestMapping(value = "/addWallet", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
	@ApiOperation(value = "新增用户积分钱包")
	public ResponseEntity addWallet(
			@ApiParam(required = true, value = "会员id") @RequestParam(required = true) long customerId
	) {
		Points customerPoints = pointsService.getByCustomerId(customerId);
		if (customerPoints != null) {
			return ServerResponse.error(ResponseCode.POINTS_USER_REPEAT, "用户积分钱包已存在");
		}
		Points points = new Points();
		points.setPointsId(SnowflakeIdWorker.generateId());
		points.setCustomerId(customerId);
		points.setAvailable(0);
		return ServerResponse.success(pointsService.insertPoints(points));
	}

	@RequestMapping(value = "/change", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
	@ApiOperation(value = "用户积分变动")
	public ResponseEntity pointsChange(
			@ApiParam(required = true, value = "会员id") @RequestParam(required = true) long customerId,
			@ApiParam(required = true, value = "积分变动数量") @RequestParam(required = true) int transPoints,
			@ApiParam(required = true, value = "积分变动标题") @RequestParam(required = true) String transTitle,
			@ApiParam(required = true, value = "积分变动流向") @RequestParam(required = true) int transType
	) throws ServiceException {
		this.pointsService.transPoints(customerId, transPoints, transTitle, transType);
		return ServerResponse.success();
	}
}
